package com.kye.express.business.waybill_search;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.widget.Toast;

import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.business.waybill.waybill_detail.WayBillDetailActivity;
import com.kye.express.databinding.ActivityWaybillSearchBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.utils.StringFormatUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.SharedPreferencesManager;
import com.kye.model.bean.waybill_search.ResultWaybillQuery;
import com.kye.model.bean.waybill_search.WaybillHistoryModel;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 运单搜索
 */
public class WaybillSearchActivity extends BaseAppCompatActivity implements WaybillSearchActivityContract.WaybillSearchView {

    private static final String KEY_SHOW_TIPS = "waybill_search_show_tips";
    private ActivityWaybillSearchBinding mBinding;
    private Context mContext;

    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();

    private WaybillSearchActivityContract.WaybillSearchViewPresenter mPresenter;

    private Dialog mDialog;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, WaybillSearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_waybill_search);
        mContext = this;
        mPresenter = new WaybillSearchActivityContract.WaybillSearchViewPresenter();
        mPresenter.bind(this);
        initView();
        initEvent();
    }

    @Override
    protected void onDestroy() {
        mPresenter.unbind();
        super.onDestroy();
    }

    private void initView() {
        showTipsView();
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(WaybillHistoryModel.class, new WaybillSearchItemViewBinder(mContext));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        RecyclerViewDivider.with(mContext)
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(mContext, 1))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mPresenter.loadHistoryDatas();
    }

    private void showTipsView() {
        boolean showTips = SharedPreferencesManager.get(KEY_SHOW_TIPS, true);
        if (showTips) {
            mBinding.llTips.setVisibility(View.VISIBLE);
        } else {
            mBinding.llTips.setVisibility(View.GONE);
        }
    }

    private void initEvent() {

        RxView.clicks(mBinding.tvCancel)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        finish();
                    }
                });

        RxView.clicks(mBinding.tvClear)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.clearHistoryDatas();
                    }
                });

        mBinding.edtNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    String expressNum = mBinding.edtNumber.getText().toString().trim();
                    if (checkWaybillString(expressNum)) {
                        mPresenter.searchWaybill(expressNum);
                    }

                    return true;
                }
                return false;
            }
        });

        RxView.clicks(mBinding.btnKnow)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        SharedPreferencesManager.commit(KEY_SHOW_TIPS, false);
                        showTipsView();
                    }
                });
    }

    private boolean checkWaybillString(String expressNum) {

        if (StringFormatUtils.isChinese(expressNum)) {
            showToast(getString(R.string.waybill_search_contain_chinese));
            return false;
        }
        if (StringFormatUtils.containsEmoji(expressNum) || "null".equals(expressNum)) {
            showToast(getString(R.string.waybill_search_content_error));
            return false;
        }
        if (TextUtils.isEmpty(expressNum) || expressNum.trim().length() == 0) {
            showToast(getString(R.string.waybill_search_hint));
            return false;
        }
        if (StringFormatUtils.hasSpecialCharacters(expressNum)) {
            showToast(getString(R.string.waybill_search_contain_special));
            return false;
        }
        if (expressNum.length() < 4) {
            showToast(getString(R.string.waybill_search_lenght_error));
            return false;
        }
        return true;
    }

    private void showToast(String message) {
        ToastManager.show(this, message, Toast.LENGTH_SHORT);
    }

    @Override
    public void onHistoryLoaded(List<WaybillHistoryModel> datas) {
        mBinding.statusLayout.showContentView();
        if (datas != null && datas.size() > 0) {
            mDatas.clear();
            for (WaybillHistoryModel item : datas) {
                mDatas.add(item);
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onHistoryEmpty() {
        mBinding.statusLayout.showEmptyView();
    }

    @Override
    public void onLoading() {
        mDialog = KyeProgressDialog.show(this, mDialog);
    }

    @Override
    public void onLoaded() {
        KyeProgressDialog.dismiss(mDialog);
    }

    @Override
    public void onLoaded(ResultWaybillQuery datas, String searchString) {
        WayBillDetailActivity.startActivity(WaybillSearchActivity.this,searchString);
    }

    @Override
    public void onError() {

    }

    @Override
    public void onError(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
    }
}
